<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, computed, watchEffect, watch, markRaw } from 'vue'
import { 
  House as _IconHome,
  Expand as _IconExpand, 
  Fold as _IconFold,
  User as _IconUser,
  Setting as _IconSetting,
  Bell as _IconBell,
  Plus as _Plus,
  Document as _Document,
  Notebook as _Notebook,
  Location as _Location,
  List as _List,
  Van as _Van,
  Money as _Money,
  UserFilled as _UserFilled
} from '@element-plus/icons-vue'

// 使用markRaw防止图标组件变成响应式
const IconHome = markRaw(_IconHome)
const IconExpand = markRaw(_IconExpand)
const IconFold = markRaw(_IconFold)
const IconUser = markRaw(_IconUser)
const IconSetting = markRaw(_IconSetting)
const IconBell = markRaw(_IconBell)
const Plus = markRaw(_Plus)
const Document = markRaw(_Document)
const Notebook = markRaw(_Notebook)
const Location = markRaw(_Location)
const List = markRaw(_List)
const Van = markRaw(_Van)
const Money = markRaw(_Money)
const UserFilled = markRaw(_UserFilled)
import { getUserRole, type UserRole } from './router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const routes = ref([])
const isCollapse = ref(false)
const activeMenu = ref('')
const currentRole = ref(getUserRole())

// 监听localStorage中角色变化（当用户重新登录时）
watchEffect(() => {
  const role = getUserRole()
  if (role !== currentRole.value) {
    currentRole.value = role
    console.log('角色已更新为:', role)
  }
})

// 监听路由变化，确保角色同步
watch(() => router.currentRoute.value.path, () => {
  const role = getUserRole()
  if (role !== currentRole.value) {
    currentRole.value = role
    console.log('路由变化，角色同步为:', role)
  }
})

// 判断当前是否为登录页
const isLoginPage = computed(() => {
  return router.currentRoute.value.path === '/login'
})

// 角色显示名称映射
const roleLabels = {
  'admin': '管理员',
  'customer': '客户',
  'courier': '配送员'
}

// 基于角色过滤菜单
const filterMenusByRole = (routes) => {
  return routes.filter(route => {
    // 如果没有设置角色限制，对所有人可见
    if (!route.meta?.roles) return true
    
    // 否则检查当前用户是否有权限
    return route.meta.roles.includes(currentRole.value)
  })
}

watchEffect(() => {
  // 确保角色变化时重新计算
  const role = currentRole.value
  
  // 获取当前用户的首页路径
  const dashboardRoutes = {
    'admin': '/admin-dashboard',
    'customer': '/customer-dashboard',
    'courier': '/courier-dashboard'
  }
  const currentDashboard = dashboardRoutes[role]
  
  // 获取所有路由，排除首页路由和具有相同路径的路由
  const allRoutes = router.getRoutes().filter(r => 
    r.meta?.title && 
    r.path !== '/' && 
    r.path !== currentDashboard &&
    r.path !== '/login' && // 排除登录页面
    !r.meta?.public && // 排除所有公开路由
    !r.meta?.hideInMenu // 排除设置了hideInMenu的路由
  )
  
  // 根据当前角色过滤路由
  let filteredRoutes = filterMenusByRole(allRoutes)
  
  // 根据order属性排序路由
  filteredRoutes = filteredRoutes.sort((a, b) => {
    // 如果两个路由都有order属性，按order值升序排序
    if (a.meta?.order !== undefined && b.meta?.order !== undefined) {
      return a.meta.order - b.meta.order
    }
    // 如果只有a有order属性，a排前面
    else if (a.meta?.order !== undefined) {
      return -1
    }
    // 如果只有b有order属性，b排前面
    else if (b.meta?.order !== undefined) {
      return 1
    }
    // 两个都没有order属性，保持原来的顺序
    return 0
  })
  
  routes.value = filteredRoutes
  
  // 设置当前活跃的菜单项
  const currentPath = router.currentRoute.value.path
  activeMenu.value = currentPath
})

const menuWidth = computed(() => {
  return isCollapse.value ? '64px' : '220px'
})

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 注意：已移除角色切换功能，系统现在完全基于登录时的用户身份来展示页面

// 获取角色名称
const getRoleName = (role: UserRole) => {
  return roleLabels[role] || '未知角色'
}

// 获取首页路由
const getHomeRoute = () => {
  const dashboardMap: Record<UserRole, string> = {
    'admin': '/admin-dashboard',
    'customer': '/customer-dashboard',
    'courier': '/courier-dashboard'
  }
  return dashboardMap[currentRole.value]
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('user_role')
  localStorage.removeItem('username')
  
  ElMessage.success('已退出登录')
  router.push('/login')
}
</script>

<template>
  <div class="app-wrapper">
    <!-- 登录页面不显示导航和菜单 -->
    <template v-if="isLoginPage">
      <router-view></router-view>
    </template>
    
    <!-- 非登录页面显示完整布局 -->
    <template v-else>
      <!-- 侧边栏 -->
      <div class="sidebar-wrapper" :style="{ width: menuWidth }">
        <div class="logo-container" :class="{ 'is-collapsed': isCollapse }">
          <div class="logo">
            <el-avatar shape="square" :size="32" class="logo-avatar">L</el-avatar>
            <span v-if="!isCollapse" class="title">物流订单系统</span>
          </div>
          <el-icon class="toggle-icon" @click="toggleCollapse">
            <component :is="isCollapse ? IconExpand : IconFold" />
          </el-icon>
        </div>
        
        <div class="menu-container">
          <el-menu
            :default-active="activeMenu"
            :collapse="isCollapse"
            :collapse-transition="false"
            router
            class="el-menu-vertical"
            :collapse-width="64">
            
            <el-menu-item index="/admin-dashboard" class="menu-item" v-if="currentRole === 'admin'">
              <el-icon><component :is="IconHome" /></el-icon>
              <template #title>
                <span>控制台</span>
              </template>
            </el-menu-item>
            
            <el-menu-item index="/customer-dashboard" class="menu-item" v-if="currentRole === 'customer'">
              <el-icon><component :is="IconHome" /></el-icon>
              <template #title>
                <span>客户首页</span>
              </template>
            </el-menu-item>
            
            <el-menu-item index="/courier-dashboard" class="menu-item" v-if="currentRole === 'courier'">
              <el-icon><component :is="IconHome" /></el-icon>
              <template #title>
                <span>配送员工作台</span>
              </template>
            </el-menu-item>
            
            <!-- 菜单项，根据路由配置动态生成 -->
            <el-menu-item 
              v-for="route in routes" 
              :key="route.path" 
              :index="route.path"
              class="menu-item">
              <el-icon>
                <component :is="route.meta.icon" />
              </el-icon>
              <template #title>
                <span>{{ route.meta.title }}</span>
              </template>
            </el-menu-item>
          </el-menu>
        </div>
      </div>
      
      <!-- 主容器 -->
      <div class="main-wrapper" :style="{ marginLeft: menuWidth }">
        <!-- 顶部栏 -->
        <header class="header-container">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="getHomeRoute()">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-if="router.currentRoute.value.meta?.title">{{ router.currentRoute.value.meta.title }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-actions">
            <el-dropdown>
              <span class="user-dropdown">
                <el-avatar :size="32" class="user-avatar">
                  <el-icon><component :is="IconUser" /></el-icon>
                </el-avatar>
                <span class="user-name">{{ getRoleName(currentRole) }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-icon><component :is="IconUser" /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-icon><component :is="IconSetting" /></el-icon>
                    系统设置
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </header>
        
        <!-- 内容区 -->
        <main class="content-container">
          <router-view v-slot="{ Component }">
            <component :is="Component" />
          </router-view>
        </main>
      </div>
    </template>
  </div>
</template>

<style scoped>
/* 整体容器 */
.app-wrapper {
  height: 100vh;
  width: 100vw;
  overflow: hidden; /* 防止出现外层滚动条 */
  position: relative;
  background-color: #f8f9fb;
}

/* 侧边栏容器 */
.sidebar-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  z-index: 999;
  background-color: #f8f9fb;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.08);
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  overflow: hidden; /* 确保侧边栏没有滚动条 */
}

/* logo区域 */
.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #ebeef5;
  overflow: hidden;
  transition: all 0.3s;
}

.logo-container.is-collapsed {
  padding: 0;
  justify-content: center;
}

.logo {
  display: flex;
  align-items: center;
}

.logo-avatar {
  background: linear-gradient(135deg, #42b983 0%, #33a06f 100%);
}

.logo .title {
  margin-left: 12px;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  white-space: nowrap;
  opacity: 1;
  transition: opacity 0.3s;
}

.toggle-icon {
  color: #606266;
  font-size: 20px;
  cursor: pointer;
}

/* 菜单容器 */
.menu-container {
  flex: 1;
  overflow-y: auto; /* 只允许菜单内部滚动 */
  overflow-x: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}

.menu-container::-webkit-scrollbar {
  display: none;
  width: 0 !important;
}

/* 菜单样式 */
.el-menu-vertical:not(.el-menu--collapse) {
  width: 100%;
  border-right: none;
}

.menu-item {
  margin: 4px 0;
}

:deep(.el-menu) {
  border-right: none;
  background-color: transparent;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  border-radius: 4px;
  margin: 8px 12px;
  color: #606266;
}

:deep(.el-menu--collapse) {
  width: 64px;
}

:deep(.el-menu--collapse .el-menu-item) {
  padding: 0 !important;
  margin: 8px 10px;
}

:deep(.el-menu-item:hover) {
  background-color: rgba(64, 158, 255, 0.08) !important;
  color: #409eff !important;
}

:deep(.el-menu-item.is-active) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #409eff !important;
  font-weight: 600;
  border-radius: 4px;
}

:deep(.el-menu-item.is-active::before) {
  content: "";
  position: absolute;
  left: 0;
  top: 12px;
  bottom: 12px;
  width: 3px;
  background-color: #409eff;
  border-radius: 0 3px 3px 0;
}

/* 主容器样式 */
.main-wrapper {
  min-height: 100vh;
  transition: margin-left 0.3s;
  display: flex;
  flex-direction: column;
  padding-top: 60px; /* 为固定的顶部栏预留空间 */
  overflow: hidden; /* 防止主容器产生滚动条 */
}

/* 顶部栏样式 */
.header-container {
  position: fixed; /* 改为固定定位 */
  top: 0;
  right: 0;
  left: 0;
  margin-left: inherit; /* 继承main-wrapper的margin-left */
  z-index: 998;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-badge {
  margin-right: 8px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 12px;
  height: 40px;
  border-radius: 20px;
  transition: all 0.3s;
  border: none;
  outline: none;
}

.user-dropdown:hover {
  background-color: rgba(64, 158, 255, 0.08);
  box-shadow: none;
  border: none;
}

:deep(.el-dropdown:focus-visible) {
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-button:focus-visible),
:deep(.el-dropdown__popper .el-dropdown-menu__item:focus-visible) {
  outline: none !important;
  box-shadow: none !important;
}

.user-avatar {
  background: linear-gradient(135deg, #36a3f7 0%, #1d77be 100%);
  color: white;
}

.user-name {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
}

/* 内容区样式 */
.content-container {
  padding: 20px;
  flex: 1;
  box-sizing: border-box;
  background-color: #f8f9fb;
  max-height: calc(100vh - 60px); /* 设置最大高度为视窗高度减去顶部导航栏高度 */
  height: calc(100vh - 60px); /* 固定高度 */
  overflow-y: auto; /* 只允许内容区域滚动 */
  padding-bottom: 40px; /* 增加底部内边距，确保最后的内容可见 */
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: rgba(144, 147, 153, 0.3) transparent; /* Firefox */
}

/* Webkit浏览器的滚动条样式 */
.content-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.content-container::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.3);
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background-color: rgba(144, 147, 153, 0.5);
}

.content-container::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 下拉菜单相关样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
}

:deep(.el-dropdown-menu) {
  padding: 6px 0;
  border-radius: 8px;
  box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08), 
              0 9px 28px 0 rgba(0, 0, 0, 0.05), 
              0 12px 48px 16px rgba(0, 0, 0, 0.03);
  border: none;
}

:deep(.el-dropdown-menu__item:hover, .el-dropdown-menu__item:focus) {
  background-color: rgba(64, 158, 255, 0.08);
  color: #409eff;
}

:deep(.el-dropdown-menu__item.is-disabled) {
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 修改通知按钮样式 */
.notification-badge :deep(.el-button) {
  border: none;
  background-color: rgba(64, 158, 255, 0.08);
}

.notification-badge :deep(.el-button:hover) {
  background-color: rgba(64, 158, 255, 0.15);
}
</style>

<style>
/* 全局样式：禁用所有Element Plus组件的默认滚动条 */
.el-table__body-wrapper,
.el-scrollbar__wrap,
.el-select-dropdown__wrap,
.el-cascader-menu__wrap,
.el-dropdown-menu,
.el-dialog__body {
  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE/Edge */
}

.el-table__body-wrapper::-webkit-scrollbar,
.el-scrollbar__wrap::-webkit-scrollbar,
.el-select-dropdown__wrap::-webkit-scrollbar,
.el-cascader-menu__wrap::-webkit-scrollbar,
.el-dropdown-menu::-webkit-scrollbar,
.el-dialog__body::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
}

/* 为html和body禁用滚动条，由内容容器管理 */
html, body {
  overflow: hidden;
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

/* 登录页面样式 */
.app-wrapper:has(> .login-container) {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: none;
}
</style>
